package cn.iwit.ctl.sys;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.iwit.model.Constant;
import cn.iwit.model.SysFunc;
import cn.iwit.model.SysRole;
import cn.iwit.model.SysUser;
import cn.iwit.model.SysUserRole;
import cn.iwit.model.UserInfo;
import cn.iwit.srv.sys.SysUserService;
import cn.iwit.util.BusiException;
import cn.iwit.util.FuncUtil;
import cn.iwit.util.HttpUtil;
import cn.iwit.util.JsonResult;
import cn.iwit.util.MD5;
import cn.iwit.util.PageInfo;
import cn.iwit.util.Tree;

@RestController
@RequestMapping(value = "/sys")
public class SysUserController {
	private static final Logger logger = LoggerFactory.getLogger(SysUserController.class);
	@Autowired
	private SysUserService sysUserService;
	
/************************************用户相关******************************************************/ 
	/**
	 * 分页查询所有用户信息或根据条件来查询
	 * @param user
	 * @param currentPage
	 * @param pageSize
	 * @param sortField
	 * @param sortOrder
	 * @return
	 */
    @RequestMapping(value = "/user/findlistByWhere", method = RequestMethod.POST)
    public JsonResult findListByWhere(SysUser user,
                                      @RequestParam(required = false, defaultValue = "1") int currentPage,
                                      @RequestParam(required = false, defaultValue = "10") int pageSize,
                                      @RequestParam(required = false, defaultValue = "modifytime") String sortField,
                                      @RequestParam(required = false, defaultValue = "desc") String sortOrder) {
        JsonResult result = new JsonResult();
        PageInfo<SysUser> page = new PageInfo<SysUser>();
        page.setPageNum(currentPage);
        page.setPageSize(pageSize);
        page.setOrderBy(sortField + " " + sortOrder);
        page = sysUserService.findUsers(user,page);
        result.setData(page);
        return result;
    }
    
    /**
     * 修改个人资料
     * @param user
     * @return
     * @throws BusiException 
     */
    @RequestMapping(value="/user/updatemyinfo")
    public JsonResult updatMyInfo(SysUser sysUser,String oldpass) throws BusiException{
        JsonResult result = new JsonResult();
        UserInfo userInfo = (UserInfo) HttpUtil.getAttribute(Constant.USERINFO);
        sysUser.setUserid(userInfo.getSysUser().getUserid());
        sysUser.setModifyuser(userInfo.getSysUser().getCname());
        
        if(userInfo.getSysUser().getPassword().equals(MD5.getMD5(oldpass))){
        	 int cnt =  sysUserService.updatePwd(sysUser);
             if(cnt>0){
         		result.setMessage("密码修改成功！");
         	}else{
         		result.setResult(1);
         		result.setMessage("密码修改失败！");
         	}
        }else{
        	result.setResult(1);
        	result.setMessage("原密码错误，请重新填写！");
        }
        return result;
    }
    
    /**
     * 保存用户信息
     * @param sysUser
     * @return
     * @throws BusiException
     */
    @RequestMapping(value="/user/save", method = RequestMethod.POST)
    public JsonResult saveUser(SysUser sysUser) throws BusiException{
    	JsonResult result = new JsonResult();
    	
    	UserInfo userInfo = (UserInfo) HttpUtil.getAttribute(Constant.USERINFO);
    	sysUser.setAdduser(userInfo.getSysUser().getCname());
    	sysUser.setModifyuser(userInfo.getSysUser().getCname());
    	
    	sysUser.setPassword(MD5.getMD5(sysUser.getPassword()));
    	int cnt = sysUserService.saveUser(sysUser);
    	if(cnt>0){
    		result.setMessage("登录名 "+ sysUser.getUsername()+" 添加成功！");
    	}else{
    		result.setResult(1);
    		result.setMessage("登录名 "+ sysUser.getUsername()+" 已存在无法添加！");
    	}
    	return result;
    }
    /**
     * 修改用户信息
     * @param sysUser
     * @return
     * @throws BusiException
     */
    @RequestMapping(value="/user/update", method = RequestMethod.POST)
    public JsonResult updateUser(SysUser sysUser) throws BusiException{
    	JsonResult result = new JsonResult();
    	
    	UserInfo userInfo = (UserInfo) HttpUtil.getAttribute(Constant.USERINFO);
    	sysUser.setModifyuser(userInfo.getSysUser().getCname());
    	sysUserService.updateUser(sysUser);
    	result.setMessage("修改 "+ sysUser.getCname()+" 信息成功！");
    	return result;
    }
    /**
     * 根据用户id删除用户信息
     * @param id
     * @return
     */
    @RequestMapping(value="/user/delete", method = RequestMethod.POST)
    public JsonResult deleteUser(String id){
    	JsonResult jsonResult = new JsonResult();
    	sysUserService.deleteUserById(id);
    	return jsonResult;
    }
    
    
/************************************角色相关******************************************************/    
    /**
     * 分页查询所有角色信息或根据条件来查询
     * @param sysRole
     * @param currentPage
     * @param pageSize
     * @param sortField
     * @param sortOrder
     * @return
     */
    @RequestMapping(value = "/role/findlistByWhere", method = RequestMethod.POST)
    public JsonResult findListByWhere(SysRole sysRole,
                                      @RequestParam(required = false, defaultValue = "1") int currentPage,
                                      @RequestParam(required = false, defaultValue = "10") int pageSize,
                                      @RequestParam(required = false, defaultValue = "modifytime") String sortField,
                                      @RequestParam(required = false, defaultValue = "desc") String sortOrder) {
        JsonResult result = new JsonResult();
        PageInfo<SysRole> page = new PageInfo<SysRole>();
        page.setPageNum(currentPage);
        page.setPageSize(pageSize);
        page.setOrderBy(sortField + " " + sortOrder);
        page = sysUserService.findRoles(sysRole, page);
        result.setData(page);
        return result;
    }
    
    /**
     * 保存角色信息
     * @param sysRole
     * @return
     * @throws BusiException
     */
    @RequestMapping(value="/role/save", method = RequestMethod.POST)
    public JsonResult saveRole(SysRole sysRole) throws BusiException{
    	JsonResult result = new JsonResult();
    	
    	UserInfo userInfo = (UserInfo) HttpUtil.getAttribute(Constant.USERINFO);
    	sysRole.setAdduser(userInfo.getSysUser().getCname());
    	sysRole.setModifyuser(userInfo.getSysUser().getCname());
    	
    	sysUserService.saveRole(sysRole);
    	result.setMessage("用户 "+ sysRole.getRolename()+" 添加成功！");
    	return result;
    }
    /**
     * 根据角色id删除角色，物理删除
     * @param id
     * @return
     */
    @RequestMapping(value="/role/delete", method = RequestMethod.POST)
    public JsonResult deleteRole(String id){
    	JsonResult jsonResult = new JsonResult();
    	sysUserService.deleteRoleById(id);
    	jsonResult.setMessage("角色信息成功！");
    	return jsonResult;
    }
    /**
     * 修改角色信息
     * @param sysRole
     * @return
     * @throws BusiException
     */
    @RequestMapping(value="/role/update", method = RequestMethod.POST)
    public JsonResult updateRole(SysRole sysRole) throws BusiException{
    	JsonResult result = new JsonResult();
    	
    	UserInfo userInfo = (UserInfo) HttpUtil.getAttribute(Constant.USERINFO);
    	sysRole.setModifyuser(userInfo.getSysUser().getCname());
    	sysUserService.updateRole(sysRole);
    	result.setMessage("修改  "+ sysRole.getRolename()+" 信息成功！");
    	return result;
    }
    
    /**
     * 查询被选中的角色下的用户
     * @param roleId
     * @return
     */
    @RequestMapping(value = "/role/findUserByRoleId", method = RequestMethod.POST)
    public JsonResult findUserByRoleId(@RequestParam long roleId) {
        JsonResult result = new JsonResult();
        result.setResult(1);
        
        PageInfo<SysUser> page = new PageInfo<SysUser>();
        page.setPageNum(1);
        page.setPageSize(2000);
        
        //获取权限下的所有用户
        page = sysUserService.findUsers(null, page);

        //获取当前角色已授权的用用户
        SysUserRole userRole = new SysUserRole();
        userRole.setRoleid(roleId);
        List<SysUserRole> userRoleList = sysUserService.findUserRole(userRole);
        Map<String, Object> map = new HashMap<String, Object>();
        result.setResult(0);
        map.put("list", page.getList());
        map.put("chosen", userRoleList);
        result.setData(map);
        return result;
    }
    
    /**
     * 保存用户角色信息
     *
     * @param roleId
     * @param userId
     * @return
     */
    @RequestMapping(value = "/role/saveAuthUserRole", method = RequestMethod.POST)
    public JsonResult saveAuthUserRole(@RequestParam long roleId, @RequestParam long[] userId) {
        JsonResult result = new JsonResult();
        result.setResult(1);
        int n = sysUserService.saveUserRole(roleId, userId);
        if (n > 0) {
            result.setMessage("操作成功！");
            result.setResult(0);
        } else {
            result.setMessage("操作失败！");
        }
        result.setResult(0);
        return result;
    }
    
    @RequestMapping(value = "/role/findFuncByRoleId", method = RequestMethod.POST)
    public JsonResult findFuncByRoleId(@RequestParam long roleId) throws BusiException {
        JsonResult result = new JsonResult();
        result.setResult(1);
        List<Tree> treeList = sysUserService.findFuncByRoleId(roleId);
        result.setData(treeList);
        result.setResult(0);
        return result;
    }
    
    @RequestMapping(value = "/role/saveRoleFunc", method = RequestMethod.POST)
    public JsonResult saveRoleFunc(@RequestParam long roleId, @RequestParam long[] funcId) {
        JsonResult result = new JsonResult();
        result.setResult(1);
        int n = sysUserService.saveRoleFunc(roleId, funcId);
        if (n > 0) {
            result.setMessage("操作成功！");
            result.setResult(0);
        } else {
            result.setMessage("操作失败！");
        }
        result.setResult(0);
        return result;
    }
/*****************************菜单相关*******************************************************/
    /**
     * 根据条件查询菜单
     *
     * @param func
     * @param sortField
     * @param sortOrder
     * @return
     */
    @RequestMapping(value = "/func/findlistTreeByWhere")
    public JsonResult findFuncListTreeByWhere(String cname,SysFunc func,
                                      @RequestParam(required = false, defaultValue = "modifytime") String sortField,
                                      @RequestParam(required = false, defaultValue = "desc") String sortOrder) {
        JsonResult result = new JsonResult();
        func.setFuncname(cname);
        List<SysFunc> list = sysUserService.findFuncList(func);
        result.setData(FuncUtil.getFatherNode(list));
        return result;
    }
    
    @RequestMapping(value = "/func/findlistByWhere", method = RequestMethod.POST)
    public JsonResult findFuncListByWhere(SysFunc func,
                                      @RequestParam(required = false, defaultValue = "1") int currentPage,
                                      @RequestParam(required = false, defaultValue = "10") int pageSize,
                                      @RequestParam(required = false, defaultValue = "modifytime") String sortField,
                                      @RequestParam(required = false, defaultValue = "desc") String sortOrder) {
        JsonResult result = new JsonResult();
        List<SysFunc> list = sysUserService.findFuncList(func);
        result.setData(list);
        return result;
    }
    /**
     * 保存菜单信息
     *
     * @param func
     * @return
     */
    @RequestMapping(value = "/func/save", method = RequestMethod.POST)
    public JsonResult saveFunc(SysFunc func) throws Exception {
        JsonResult result = new JsonResult();
        result.setResult(1);
        UserInfo userInfo = (UserInfo) HttpUtil.getAttribute(Constant.USERINFO);
        func.setAdduser(userInfo.getSysUser().getCname());
        func.setAddtime(new Date());
        func.setModifyuser(userInfo.getSysUser().getCname());
        func.setModifytime(new Date());
        int n = sysUserService.saveFunc(func);
        if (n > 0) {
            result.setMessage("操作成功！");
            result.setResult(0);
        } else {
            result.setMessage("操作失败！");
        }
        return result;
    }
    
    /**
     * 保存菜单信息
     *
     * @param func
     * @return
     */
    @RequestMapping(value = "/func/update", method = RequestMethod.POST)
    public JsonResult updateFunc(SysFunc func) throws Exception {
    	  JsonResult result = new JsonResult();
          result.setResult(1);
          UserInfo userInfo = (UserInfo) HttpUtil.getAttribute(Constant.USERINFO);
          func.setModifyuser(userInfo.getSysUser().getUsername());
          func.setModifytime(new Date());
          int n = sysUserService.updateFunc(func);
          if (n > 0) {
              result.setMessage("操作成功！");
              result.setResult(0);
          } else {
              result.setMessage("操作失败！");
          }
          return result;
    }
    

    /**
     * 删除信息 支持批量删除
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/func/delete", method = RequestMethod.POST)
    public JsonResult deleteFunc(String id) {
        JsonResult result = new JsonResult();
        result.setResult(1);

        int[] n = sysUserService.deleteFunc(id);
        if (n.length > 0) {
            result.setMessage("操作成功！");
            result.setResult(0);
        } else {
            result.setMessage("操作失败！");
        }
        return result;
    }
    
}
